#encoding=utf8
'''
Created on Sep 15, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
import os
import json

import xlrd

from django.http.response import HttpResponseRedirect, HttpResponse, Http404
from django.template.loader import get_template
from django.template.context import RequestContext
from django.shortcuts import render_to_response
from django.db.models.query_utils import Q
from django.contrib.auth.models import User
from django.utils import timezone

from app_info.models import App, Studio, UserGroup, AppVersion, ProductionTeam,\
    StudioCloud, AppExtraInfo, Company
import settings
from django.contrib.auth.decorators import login_required
import csv
import xlwt
from sub_info.models import ReviewStatus, SubInfo
from utils import JsonResponse, api_call
from django.core.exceptions import PermissionDenied
import datetime


def _get_data(division=None, teams=None, clouds=None, studios=None, pjms=None):
    '''
    division: division id list
    '''
    base = AppVersion.objects.exclude(editor='imported@smalltreemedia.com')\
        .filter(status__in=['S', 'L']).order_by('date_submitted')
    #  filter division
    division = UserGroup.objects.filter(id__in=division) if division else []
    if division:
        base = base.filter(prd_team__group__in=division)

    #  filter teams
    teams = ProductionTeam.objects.filter(id__in=teams) if teams else []
    if teams:
        base = base.filter(prd_team__in=teams)

    # filter pjms
    if pjms:
        base = base.filter(owner__in=pjms)

    # filter clouds
    clouds_studios = [s.pk for s in Studio.objects.filter(cloud__id__in=clouds)] if clouds else []
    if clouds_studios:
        base = base.filter(app__studio__id__in=clouds_studios)

    # filter studios
    if studios:
        base = base.filter(app__studio__id__in=studios)

    date_list = base.values_list('date_submitted', flat=True)
    month_list = []
    for date in date_list:
        if not date:
            continue
        date = str(date).split('-')
        month = (date[0], date[1])
        if not month in month_list:
            month_list.append(month)
    ios_new, ios_update, gp_new, gp_update, amz_new, amz_update = [], [], [], [], [], []
    for m in month_list:
        all_data = base.filter(date_submitted__year=m[0], date_submitted__month=m[1])
        ios_new_count = all_data.filter(type='N', app__app_store='iTunes App Store').count()
        ios_update_count = all_data.filter(type='U', app__app_store='iTunes App Store').count()
        gp_new_count = all_data.filter(type='N', app__app_store='Google Play').count()
        gp_update_count = all_data.filter(type='U', app__app_store='Google Play').count()
        amz_new_count = all_data.filter(type='N', app__app_store='Amazon App Store').count()
        amz_update_count = all_data.filter(type='U', app__app_store='Amazon App Store').count()

        new_tooltip = {'formatter': '%s-%s: <br />Amazon - New: %s<br />GP - New: %s<br />iOS - New: %s' %\
                       (m[0], m[1], amz_new_count, gp_new_count, ios_new_count)}
        update_tooltip = {'formatter': '%s-%s: <br />Amazon - Update: %s<br />GP - Update: %s<br />iOS - Update: %s' %\
                          (m[0], m[1], amz_update_count, gp_update_count, ios_update_count)}

        ios_new.append({'value': ios_new_count, 'tooltip': new_tooltip})
        gp_new.append({'value': gp_new_count, 'tooltip': new_tooltip})
        amz_new.append({'value': amz_new_count, 'tooltip': new_tooltip})

        ios_update.append({'value': ios_update_count, 'tooltip': update_tooltip})
        gp_update.append({'value': gp_update_count, 'tooltip': update_tooltip})
        amz_update.append({'value': amz_update_count, 'tooltip': update_tooltip})

    return {'month_list': ['%s-%s' % (m[0], m[1]) for m in month_list], 'ios_new': ios_new, 'ios_update': ios_update,
            'gp_new': gp_new, 'gp_update': gp_update, 'amz_new': amz_new, 'amz_update': amz_update}


def get_production_output(req):
    '''
    view monthly production output chart in report center.
    '''
    if req.is_ajax():
        t = get_template('base/charts.html')

        division = req.REQUEST.get('division')
        teams = req.REQUEST.get('teams')
        clouds = req.REQUEST.get('clouds')
        studios = req.REQUEST.get('studios')
        pjms = req.REQUEST.get('pjms')

        division = division.strip(',').split(',') if division else None
        teams = teams.strip(',').split(',') if teams else None
        clouds = clouds.strip(',').split(',') if clouds else None
        studios = studios.strip(',').split(',') if studios else None
        pjms = pjms.strip(',').split(',') if pjms else None

        html = t.render(RequestContext(req, _get_data(division, teams, clouds, studios, pjms)))
        return JsonResponse({'status': 1, 'html': html})
    ctx = _get_data()

    my_divisions = UserGroup.objects.all()
    my_teams = ProductionTeam.objects.all()
    my_pjms = User.objects.filter(is_active=True, is_staff=True,
        groups__name__in=['Project Manager', 'Division Head'])
    my_studios = Studio.objects.all()
    my_clouds = StudioCloud.objects.all()

    names = req.user.groups.values_list('name', flat=True)
    if 'Division Head' in names or 'Project Manager' in names:
        base_teams = ProductionTeam.objects.filter(user=req.user)
        my_divisions = list(set([pt.group for pt in base_teams]))
        my_teams = list(set(base_teams))
        my_pjms = []
        for pt in base_teams:
            users = pt.user.all()
            for u in users:
                my_pjms.append(u)
        my_pjms = list(set(my_pjms))
        my_studios = []
        for pt in base_teams:
            ss = pt.studios.all()
            for s in ss:
                my_studios.append(s)
        my_studios = list(set(my_studios))
        my_clouds = list(set([s.cloud for s in my_studios]))
    ctx.update({'title': 'Monthly Production Output Overview',
                'my_clouds': my_clouds,
                'my_studios': my_studios,
                'my_division': my_divisions,
                'my_teams': my_teams,
                'my_pjms': my_pjms})
    return render_to_response('base/production_output.html', RequestContext(req, ctx))


def landing(req):
    return HttpResponseRedirect('/admin/')


def search_for_info(req):
    if req.method == "POST":
        entry = None
        prj_code = req.POST.get('app_code', '').strip()
        if prj_code:
            entry = App.objects.filter(Q(prj_code=prj_code) | Q(old_prj_code=prj_code),
                status='V')
        return render_to_response('search.html', RequestContext(req,
            {'result': True, 'entry': entry[0] if entry else None, 'default': prj_code}))
    return render_to_response('search.html', RequestContext(req))


def get_bundle_id_prefix(req):
    """
    return bundle id choices for given studio, in json type
    """
    try:
        studio = Studio.objects.get(id=req.REQUEST.get('id'))
        pre = studio.bundle_id.splitlines()
    except Exception, e:
        pre = []
    return HttpResponse(json.dumps({'pre': pre}),
        mimetype='application/json')


def get_available_studios(req):
    '''
    get available studios for request user, call via js ajax.
    '''
    if not req.is_ajax():
        raise Http404
    store = req.REQUEST.get('store')
    if not store:
        return HttpResponse(json.dumps({'studios': []}))
    if req.user.is_superuser or req.user.groups.filter(name='Post-production Staff').exists():
        return HttpResponse(json.dumps({'studios': [{'id': s.pk,
            'name': s.__unicode__()} for s in Studio.objects.filter(
                available_store__contains=store)]}))
    teams = ProductionTeam.objects.filter(user=req.user)
    studios = []
    for t in teams:
        studios += t.studios.filter(available_store__contains=store)
    studios = list(set(studios))
    studios = [{'id': s.pk, 'name': s.__unicode__()} for s in studios]
    return HttpResponse(json.dumps({'studios': studios}))


def get_included_studios(req):
    '''
    get included studios of a division, call via js ajax.
    '''
    if not req.is_ajax():
        raise Http404
    team_id = req.REQUEST.get('id')
    studios = []
    try:
        team = ProductionTeam.objects.get(id=team_id)
    except Exception, e:
        return JsonResponse({'status': 1, 'studios': studios})
    studios = team.get_included_studios()
    studios = [{'id': s.pk, 'name': s.__unicode__()} for s in studios]
    return JsonResponse({'status': 1, 'studios': studios})


def get_code_format(req):
    """
    return app code format for given studio, in json type
    """
    try:
        studio = Studio.objects.get(id=req.REQUEST.get('id'))
        store = req.REQUEST.get('store')
        if store == 'iTunes App Store':
            res = studio.ios_code_format or ""
        elif store == 'Google Play':
            res = studio.gp_code_format or ""
        elif store == 'Amazon App Store':
            res = studio.amz_code_format or ""
        else:
            res = ""
    except Exception, e:
        res = ""
    return HttpResponse(json.dumps({'res': res}), mimetype='application/json')


def get_current_user(req):
    res = {}
    if req.user.is_authenticated():
        res = {'uid': req.user.id, 'uname': req.user.username}
    return HttpResponse(json.dumps({'res': res}), mimetype='application/json')


def get_company(req):
    data = []
    for group in req.user.groups.all():
        if group.permissions.filter(codename__in=['add_app', 'change_app']).exists():
            if {'id': str(group.companygroup.company.id), 'name': str(group.companygroup.company.display_name)} not in data:
                data.append({'id': str(group.companygroup.company.id), 'name': str(group.companygroup.company.display_name)})
    print data
    return HttpResponse(json.dumps({'data': data, 'len': len(data)}), mimetype='application/json')


def import_old_apps(req):
    if not req.method == 'POST':
        return render_to_response('import_old_apps.html', RequestContext(req))
    f = req.FILES.get('file')
    n, e = os.path.splitext(f.name)
    path = "%s/%s-%s.%s" % (settings.IMPORTED_APPS_DIR, n, timezone.now().strftime('%Y%m%d%H%M%S'), e)
    with open(path, 'wb+') as dest:
        for chunk in f.chunks():
            dest.write(chunk)
    data = xlrd.open_workbook(path)
    table = data.sheets()[0]
    nrows = table.nrows
    error_lines = []
    exists_apps = []
    for i in range(nrows):
        if i == 0:
            continue
        try:
            store = table.row_values(i)[0]
            platform = 'A' if table.row_values(i)[1] == 'Android' else 'I'
            studio = Studio.objects.get(pub_name=table.row_values(i)[2])
            bundle_id_prefix = table.row_values(i)[3]
            bundle_id_suffix = table.row_values(i)[4]
            app_code = table.row_values(i)[5]
            app_name = table.row_values(i)[6]
            app_id = table.row_values(i)[7]
            app_id = str(int(float(app_id))) if app_id else ""
            flurry_key = table.row_values(i)[8]
            sub_doc_local = table.row_values(i)[9]
            display_name = table.row_values(i)[10]
        except Exception, e:
            error_lines.append("%s (%s)" % (i + 1, e))
            continue
        store_link = ''
        if store == 'iTunes App Store':
            store_link = 'https://itunes.apple.com/app/id%s?mt=8' % app_id if app_id else ""
        elif store == 'Google Play':
            store_link = 'https://play.google.com/store/apps/details?id=%s%s'\
                % (bundle_id_prefix, bundle_id_suffix)
        elif store == 'Amazon App Store':
            store_link = 'http://www.amazon.com/gp/mas/dl/android?p=%s%s'\
                % (bundle_id_prefix, bundle_id_suffix)
        latest = App.objects.all().order_by('-prd_id')[:1]
        if latest:
            num_app = int(latest[0].prd_id[2:]) + 1
        else:
            num_app = 20001
        app, c = App.objects.get_or_create(prj_code=app_code,
            defaults={'prd_id': 'CD%s' % num_app, 'app_store': store, 'platform': platform,
                      'studio': studio, 'bundle_id_prefix': bundle_id_prefix,
                      'bundle_id_suffix': bundle_id_suffix, 'app_name': app_name,
                      'editor': "imported@smalltreemedia.com",
                      'app_id': app_id, 'status': 'V', 'store_link': store_link,
                      'flurry_key': flurry_key, 'valid_time': None,
                      'valid_person': "imported@smalltreemedia.com"})
        app.flurry_key = flurry_key
        app.save()
        AppExtraInfo.objects.get_or_create(app=app)
        app.appextrainfo.media_local = sub_doc_local
        sub_doc_remote = sub_doc_local.replace('\\', '/')
        if ':' in sub_doc_remote:
            sub_doc_remote = sub_doc_remote.split(':')
            sub_doc_remote = 'https://www.dropbox.com/home/Small Tree Media/Project Submission Doc%s' % sub_doc_remote[1]
        app.appextrainfo.media_remote = sub_doc_remote
        app.appextrainfo.display_name = display_name
        app.appextrainfo.save()
        if not c:
            exists_apps.append(app.prj_code)
            continue
        owner = User.objects.get(email='imported@smalltreemedia.com')
        v, created = AppVersion.objects.get_or_create(app=app, code='1.0', type='N',
            purpose='New App', defaults={'editor': "imported@smalltreemedia.com",
                                         'owner': owner.pk, 'status': 'L'})
        if created:
            current_year = timezone.now().year
            current_month = timezone.now().month
            current_day = timezone.now().day
            latest = AppVersion.objects.exclude(id=v.pk).filter(create_time__year=current_year,
                create_time__month=current_month, create_time__day=current_day).order_by('-log_id')[:1]
            if latest:
                num = int(latest[0].log_id[-3:]) + 1
            else:
                num = 1
            v.log_id = 'PV%s%s%s%s' % (current_year, '%02i' % current_month,
                '%02i' % current_day, '%03i' % num)
            v.save()
    return render_to_response('import_old_apps.html', RequestContext(req,
        {'results': True, 'error_lines': error_lines, 'exists_apps': exists_apps}))


def tmp_export2():
    book = xlrd.open_workbook('/home/develop/app_list_20150505.xlsx')
    table = book.sheets()[0]
    nrows = table.nrows
    print nrows
    with open('/home/develop/app_list_with_flurry_key_20150505.csv', 'wb') as f:
        w = csv.writer(f)
        for i in xrange(1, nrows):
            if not table.row_values(i)[0] == 'CD':
                continue
            market = table.row_values(i)[8]
            if market == 'ios':
                key = table.row_values(i)[4]
                app = App.objects.filter(app_id=str(int(key)))[:1]
            elif market == 'google-play':
                key = table.row_values(i)[3]
                pre, suf = key.strip().rsplit('.', 1)
                app = App.objects.filter(bundle_id_prefix=pre + '.', bundle_id_suffix=suf)[:1]
            else:
                continue
            if not app:
                print 'line: %s, %s not found' % (i + 1, table.row_values(i)[1].encode('utf8'))
                continue
            app = app[0]
            v1 = app.appversion_set.filter(code='1.0')[:1]
            try:
                coordinator = User.objects.get(id=v1[0].owner).username
            except Exception, e:
                print e
                coordinator = ''
            w.writerow([table.row_values(i)[1].encode('utf8'), str(int(table.row_values(i)[4])),
                        app.flurry_key, app.prj_code,
                        coordinator])
    f.close()


def tmp_export():
    apps = App.objects.filter(status='V')
    headers = ['Production Groups', 'Project Code', 'Product Line', 'Platform',
        'Coordinator', 'Studio Name', 'Bundle ID', 'Flurry ID', 'App ID',
        'V1.0 Status', 'Release Date', 'Access Code(Flurry)', 'Product Brief Code']
    with open('/home/develop/pts_app_list_%s.csv' % datetime.datetime.now().date(), 'wb') as f:
        w = csv.writer(f)
        w.writerow(headers)
        for app in apps:
            v1 = app.appversion_set.filter(code='1.0')[:1]
            if v1:
                v1 = v1[0]
            else:
                continue
            coordinator = User.objects.get(id=v1.owner)
            team = ProductionTeam.objects.filter(user=coordinator)[:1]
            group = team[0].group.name if team else ''
            try:
                w.writerow([group, app.prj_code, '', app.app_store,
                    coordinator.username, app.studio.pub_name,
                    app.get_full_bundle_id(), app.flurry_key, app.app_id,
                    v1.get_status_display(), v1.get_release_date(), '',
                    v1.ref_id or ''])
            except Exception, e:
                print e
                print app
                continue
    f.close()


def get_last_week_apps(last_week=None):
    today = timezone.now().date()
    if not last_week:
        last_week = today.replace(day=today.day - 8)
    else:
        last_week = datetime.datetime.strptime(last_week, '%Y-%m-%d').date()
    tasks = AppVersion.objects.filter(code='1.0', status='L')
    with open('/home/develop/pts_last_week_apps.csv', 'wb') as f:
        w = csv.writer(f)
        w.writerow(['App Store', 'Coordinator', 'App Code', 'App Name',
            'Bundle ID', 'Release Date'])
        for t in tasks:
            if t.get_release_date():
                if last_week < t.get_release_date() < today:
                    w.writerow([t.app.app_store, User.objects.get(id=t.owner).username,
                        t.app.prj_code, t.app.app_name, t.app.get_full_bundle_id(),
                        t.get_release_date()])
    f.close()


def get_division_apps(start_date, end_date, type=None, division_name='all'):
    users = []
    if not division_name == 'all':
        try:
            division = UserGroup.objects.get(name=division_name)
            for t in division.productionteam_set.all():
                users += t.user.values_list('pk', flat=True)
            users = list(set(users))
        except Exception, e:
            print e
            return
    start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d').date()
    end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d').date()
    tasks = AppVersion.objects.filter(status='L')
    if type:
        tasks = tasks.filter(type=type)
    if users:
        tasks = tasks.filter(owner__in=users)
    with open('/home/develop/pts_%s_%s_%s-%s.csv' % (division_name,
        'New' if type == 'N' else 'Update', start_date, end_date), 'wb') as f:
        w = csv.writer(f)
        w.writerow(['App Store', 'App Code', 'Version', 'Release Date', 'Task ID',
            'App Name (Production)', 'Production Type', 'Studio'])
        for t in tasks:
            if t.get_release_date():
                if start_date <= t.get_release_date() <= end_date:
                    w.writerow([t.app.app_store, t.app.prj_code, t.code,
                        t.get_release_date(), t.log_id, t.app.app_name.encode('utf8'),
                        t.get_type_display(), t.app.studio.__unicode__()])
    f.close()


@login_required()
def export_apps(req):
    raise PermissionDenied  # block the method
    format = req.REQUEST.get('format')
    if not format in ('xls', 'csv'):  # TODO: json & xml
        raise Http404
    apps = App.objects.all()
    headers = ['Product ID', 'App Code', 'App Name', 'Bundle ID', 'Flurry Key',
        'Apple ID']
    file_name = 'PTS_APPS_%s.%s' % (timezone.localtime(timezone.now()).strftime('%Y%m%d%H%M%S'), format)
    file_path = "%s/%s" % (settings.EXPORTED_APPS_DIR, file_name)
    if format == 'csv':
        with open(file_path, 'wb') as f:
            w = csv.writer(f)
            w.writerow(headers)
            for app in apps:
                flurry_key = app.flurry_key or ""
                w.writerow([app.prd_id, app.prj_code, app.app_name.encode('utf8'),
                    app.get_full_bundle_id().encode('utf8'), flurry_key.encode('utf8'), app.app_id or ''])
        f.close()
    elif format == 'xls':
        book = xlwt.Workbook(encoding='utf8')
        sheet = book.add_sheet('PTS APPS')
        for k, v in enumerate(headers):
            sheet.write(0, k, v)
        for k, v in enumerate(apps, start=1):
            sheet.write(k, 0, v.prd_id)
            sheet.write(k, 1, v.prj_code)
            sheet.write(k, 2, v.app_name.encode('utf8'))
            sheet.write(k, 3, v.get_full_bundle_id())
            sheet.write(k, 4, v.flurry_key or "")
            sheet.write(k, 5, v.app_id)
        book.save(file_path)
    return HttpResponseRedirect('/exported_apps/%s' % file_name)


@login_required()
def export_version(req):
    if not req.user.is_superuser:
        raise PermissionDenied  # block the method
    filter_status = req.REQUEST.get('status')
    version = AppVersion.objects.all()
    if filter_status:
        version = version.filter(status__in=filter_status)
    lived = ReviewStatus.objects.filter(status='RE').values_list('sub_info', flat=True)
    headers = ['Production Task ID', 'Product ID', 'App Code', 'App Name', 'Platform',
        'App Store', 'Production Type', 'Version Num.', 'Studio Cloud', 'Studio',
        'Product Owner', 'Project Coordinator', 'Division', 'Production Team',
        'Programmer', 'Submitted Date', 'Release Date',
        'Status', 'Apple ID', 'Bundle ID', 'Flurry Key', 'Price']
    file_name = 'PTS_APPVERSION_%s.%s' % (timezone.localtime(timezone.now()).strftime('%Y%m%d%H%M%S'), 'xls')
    file_path = "%s/%s" % (settings.EXPORTED_APPS_DIR, file_name)
    book = xlwt.Workbook(encoding='utf8')
    sheet = book.add_sheet('PTS APPVERSION')
    for k, v in enumerate(headers):
        sheet.write(0, k, v)
    for k, v in enumerate(version, start=1):
        flurry_key = ''
        release_date = ''
        owner = ''
        coordinator = ''
        price = ''
        subinfo = SubInfo.objects.filter(app=v.app, version=v.code)
        submitted = subinfo.values_list('id', flat=True)
        for s in submitted:
            if s in lived:
                r = ReviewStatus.objects.get(sub_info__id=s)
                release_date = r.release_date.strftime('%Y-%m-%d') if r.release_date else ''
                break
        flurry_key = v.app.flurry_key or ''
        owner = v.product_owner
        cid = v.owner
        try:
            coordinator = User.objects.get(id=cid)
        except User.DoesNotExist:
            pass
        subinfo = subinfo.filter(validation='V')[:1]
        if subinfo:
            price = subinfo[0].get_price()
        team = ProductionTeam.objects.filter(user=coordinator)[:1]
        team = team[0] if team else None
        division = team.group if team else None

        sheet.write(k, 0, v.log_id)
        sheet.write(k, 1, v.app.prd_id)
        sheet.write(k, 2, v.app.prj_code)
        sheet.write(k, 3, v.app.app_name.encode('utf8'))
        sheet.write(k, 4, v.app.get_platform_display())
        sheet.write(k, 5, v.app.app_store)
        sheet.write(k, 6, v.get_type_display())
        sheet.write(k, 7, 'V%s' % v.code)
        sheet.write(k, 8, v.app.studio.cloud.cloud_id)
        sheet.write(k, 9, v.app.studio.__unicode__())
        sheet.write(k, 10, owner.encode('utf8'))
        sheet.write(k, 11, coordinator.username)
        sheet.write(k, 12, division.__unicode__() if division else '')
        sheet.write(k, 13, team.__unicode__() if team else '')
        sheet.write(k, 14, v.programmer or '')
        sheet.write(k, 15, str(v.date_submitted or ''))
        sheet.write(k, 16, release_date)
        sheet.write(k, 17, v.get_status_display())
        sheet.write(k, 18, v.app.app_id or "")
        sheet.write(k, 19, v.app.get_full_bundle_id())
        sheet.write(k, 20, flurry_key)
        sheet.write(k, 21, price)
    book.save(file_path)
    return HttpResponseRedirect('/exported_apps/%s' % file_name)


def register_apm():
    results = []
    app_list = list(set(AppVersion.objects.filter(status='L')\
        .order_by('app').values_list('app_id', flat=True)))
    app_list = App.objects.filter(id__in=app_list, status='V').exclude(prj_code='PARTY2059G')[:1]
    for app in app_list:
        ctx = {'product_id': app.prd_id, 'app_code': app.prj_code,
               'alt_app_code': app.old_prj_code, 'app_name': app.app_name,
               'pub_app_name': app.pub_name, 'bundle_id_prefix': app.bundle_id_prefix,
               'bundle_id_suffix': app.bundle_id_suffix,
               'full_bundle_id': app.get_full_bundle_id(),
               'platform': app.get_platform_display(), 'app_store': app.app_store,
               'apple_id': app.app_id, 'store_link': app.store_link,
               'publish_studio': '%s - %s' % (app.studio.custom_id, app.studio.pub_name),
               'studio_cloud': app.studio.cloud.cloud_id,
               'initial_release_date': str(app.get_initial_release_date()),
               'flurry_key': app.flurry_key, 'division': app.get_division(),
               'team': app.get_team()}
        versions = [{'task_id': v.log_id,
                     'coordinator': v.get_coordinator(),
                     'version_num': v.code,
                     'release_date': str(v.date_released) or "",
                     'release_notes': v.change_list,
                     'has_iap': True if v.iap_required == 'Y' else False,
                     'has_ads': True if v.ads_required == 'Y' else False,
                     'has_cross_promo': True if v.cross_promo_required == 'Y' else False}\
                    for v in app.appversion_set.filter(status='L')]
        ctx.update({'versions': versions})
        results.append(ctx)
    data = {'count': app_list.count(), 'results': results}
    print 'count: ', data['count']
    rtn = api_call('http://10.0.18.2:8000/app_info/new/register/',
        json.dumps(data), 'POST', {'Content-Type': 'application/json'})
    print rtn
